package com.jt.tenant.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.jt.tenant.activity.CarLocationActivity;
//import com.jt.tenant.activity.DiagnoseActivity;
import com.jt.tenant.activity.FreeWayStateShowActivity;
//import com.jt.tenant.activity.GetIntegralActivity;
//import com.jt.tenant.activity.LookIllegalCarPositionActivity;
//import com.jt.tenant.activity.NewInsQuoteActivity;
//import com.jt.tenant.activity.NewWaitPricingActivity;
//import com.jt.tenant.activity.NewWaitQuoteActivity;
import com.jt.tenant.activity.InsCheckSelectActivity;
import com.jt.tenant.activity.InsQuoteActivity;
import com.jt.tenant.activity.NotifyFenceActivity;
//import com.jt.tenant.activity.OrderDetailsActivity;
//import com.jt.tenant.activity.PersonActivity;
//import com.jt.tenant.activity.SelectInsuranceActivity;
import com.jt.tenant.activity.ShockReportActivity;
import com.jt.tenant.activity.TravelReportActivity;
//import com.jt.tenant.adapter.InsuranceSelectAdapter;
import com.jt.tenant.app.JTApplication;
//import com.jt.tenant.conn.GetMyOrder1;
import com.jt.tenant.conn.GetQueryFence;
import com.jt.tenant.widget.Tools;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p/>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";
    private String message_id;//消息id
    private String obdid;//obdID
    private String vincode;//车架号
    private String create_time;//服务器创建时间
    private String message_type;//消息类型
    private String message_level;//消息级别越小越高
    private String title;//标题
    private String message_name;//消息名称
    private String message_from;//消息来源
    private String message;//消息内容
    private String value;//消息值
    private JSONObject jsonObject_value;//消息值JSON格式
    private String alert;//提醒内容
    private String address;//地址
    private String lat;//纬度
    private String lon;//经度
//    private List<GetMyOrder1.Field> fields;//接收4S店确认订单转跳订单详情页-商品列表
//    private List<InsuranceSelectAdapter.InsuranceItem> insuranceItemList;//保险项目列表


    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.e(TAG, "[JPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.e(TAG, "[JPushReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[JPushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
            processCustomMessage(context, bundle);

        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.e(TAG, "[JPushReceiver] 接收到推送下来的通知");
            Log.e("SH", JTApplication.jtPreferences.readPhone());
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            try {
                String jsonStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
                JSONObject jsonObject = new JSONObject(jsonStr);
                message_type = jsonObject.optString("message_type");
                message_id = jsonObject.optString("message_id");
                obdid = jsonObject.optString("obdid");
                vincode = jsonObject.optString("vincode");
                create_time = jsonObject.optString("create_time");
                message_level = jsonObject.optString("message_level");
                title = jsonObject.optString("title");
                message_name = jsonObject.optString("message_name");
                message_from = jsonObject.optString("message_from");
                message = jsonObject.optString("message");
                value = jsonObject.optString("value");
                if (message_type.equals("7") || message_type.equals("8") || message_type.equals("15") || message_type.equals("16")) {
                    jsonObject_value = new JSONObject(value);
                }
                alert = jsonObject.optString("alert");
                address = jsonObject.optString("address");
                lat = jsonObject.optString("lat");
                lon = jsonObject.optString("lng");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e(TAG, "[JPushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else {
            if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.e(TAG, "[JPushReceiver] 用户点击打开了通知");

                try {
                    String jsonStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
                    JSONObject jsonObject = new JSONObject(jsonStr);
                    message_type = jsonObject.optString("message_type");
                    message_id = jsonObject.optString("message_id");
                    obdid = jsonObject.optString("obdid");
                    vincode = jsonObject.optString("vincode");
                    create_time = jsonObject.optString("create_time");
                    message_level = jsonObject.optString("message_level");
                    title = jsonObject.optString("title");
                    message_name = jsonObject.optString("message_name");
                    message_from = jsonObject.optString("message_from");
                    message = jsonObject.optString("message");
                    value = jsonObject.optString("value");
                    if (message_type.equals("7") || message_type.equals("8") || message_type.equals("15") || message_type.equals("16")|| message_type.equals("30")) {

                        jsonObject_value = new JSONObject(value);

                    }

                    alert = jsonObject.optString("alert");
                    address = jsonObject.optString("address");
                    lat = jsonObject.optString("lat");
                    lon = jsonObject.optString("lng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                boolean isBackground = Tools.isApplicationBroughtToBackground(context);
                String activitystr = Tools.getRunningActivityName(context);

                if (message_type.equals("0")) {
                    //obd激活

                } else if (message_type.equals("1")) {
                    //电子围栏越界
                    if (activitystr != null && !activitystr.equals("null") && !activitystr.equals("")) {

                        String jsonStr = bundle.getString(JPushInterface.EXTRA_EXTRA);
                        GetQueryFence.Fence fence = null;
                        try {
                            JSONObject jsonObject = new JSONObject(jsonStr);

                            fence = new GetQueryFence.Fence();

                            fence.rangeNum = jsonObject.optDouble("rangeNum");

                            fence.remark = jsonObject.optString("remark");

                            fence.status = jsonObject.optString("status");

                            fence.lng = jsonObject.optDouble("fencelng");

                            fence.id = jsonObject.optString("id");

                            fence.outOpen = jsonObject.optString("outOpen");

                            fence.inOpen = jsonObject.optString("inOpen");

                            fence.address = jsonObject.optString("address");

                            fence.obdId = jsonObject.optString("obdId");

                            fence.name = jsonObject.optString("name");

                            fence.createTime = jsonObject.optString("createTime");

                            fence.userId = jsonObject.optString("userId");

                            fence.addressType = jsonObject.optString("addressType");

                            fence.lat = jsonObject.optDouble("fencelat");

                            fence.wgsLat = jsonObject.optDouble("wgsLat");

                            fence.wgsLng = jsonObject.optDouble("wgsLng");

                            fence.poiName = jsonObject.optString("poiName");

                            fence.poiAddress = jsonObject.optString("poiAddress");

                            fence.recommend_id = jsonObject.optString("recommend_id");

                            fence.dataFrom = jsonObject.optString("dataFrom");

                            fence.outStat = jsonObject.optString("outStat");

                            fence.inStat = jsonObject.optString("inStat");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if (activitystr.equals("com.jt.tenant.activity.NotifyFenceActivity")) {
                            if (NotifyFenceActivity.refreshLinstener != null) {
                                NotifyFenceActivity.refreshLinstener.refresh(fence, lat, lon, isBackground);
                            }

//								JTApplication.INSTANCE.finishActivity(NotifyFenceActivity.class);
                        } else {

                            Intent i = new Intent(context, NotifyFenceActivity.class);
//        	            i.putExtras(bundle);
                            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            i.putExtra("Fence", fence);
                            i.putExtra("lat", lat);
                            i.putExtra("lng", lon);
                            i.putExtra("isback", isBackground);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                            context.startActivity(i);
                        }

                    }


                } else if (message_type.equals("2")) {
                    //异常异动

                } else if (message_type.equals("3")) {
                    //碰撞震动唤醒
                    Intent i = new Intent(context, ShockReportActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    i.putExtra("title", title)
                            .putExtra("message_name", message_name)
                            .putExtra("message_from", message_from)
                            .putExtra("message", message)
                            .putExtra("value", value)
                            .putExtra("alert", alert)
                            .putExtra("address", address)
                            .putExtra("lat", lat)
                            .putExtra("create_time", Tools.getTime4(create_time))
                            .putExtra("lon", lon);
                    context.startActivity(i);


                } else if (message_type.equals("4")) {
                    //故障码
//                    Intent i = new Intent(context, DiagnoseActivity.class);
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                    i.putExtra("title", title)
//                            .putExtra("message_name", message_name)
//                            .putExtra("message_from", message_from)
//                            .putExtra("message", message)
//                            .putExtra("value", value)
//                            .putExtra("alert", alert)
//                            .putExtra("address", address)
//                            .putExtra("lat", lat)
//                            .putExtra("create_time", create_time)
//                            .putExtra("lon", lon);
//                    context.startActivity(i);

                } else if (message_type.equals("5")) {
                    //起火
                    Intent i = new Intent(context, CarLocationActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    i.putExtra("longitude", lon)
                            .putExtra("latitude", lat)
                            .putExtra("location", "车辆发动");
                    JTApplication.INSTANCE.finishActivity(CarLocationActivity.class);
                    context.startActivity(i);


                } else if (message_type.equals("6")) {
                    //熄火

                    Intent i = new Intent(context, CarLocationActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    i.putExtra("longitude", lon);
                    i.putExtra("latitude", lat);
                    i.putExtra("location", "停在这里");

                    JTApplication.INSTANCE.finishActivity(CarLocationActivity.class);
                    context.startActivity(i);

                } else if (message_type.equals("7")) {
                    //购险报价
//                    Intent i = new Intent(context, SelectInsuranceActivity.class);
//
//
//                    Bundle mbundle = new Bundle();
//
//                    mbundle.putString("ORDER_ID", String.valueOf(jsonObject_value.optInt("id")));
//
//                    mbundle.putString("INSURANCE_ID", String.valueOf(jsonObject_value.optInt("insurance_id")));
//
//                    mbundle.putString("INSURANCE_TYPE", String.valueOf(jsonObject_value.optInt("insurance_type")));
//
//                    JSONArray item_arr = jsonObject_value.optJSONArray("data");
//
//                    insuranceItemList = new ArrayList<>();
//
//                    if (item_arr != null) {
//
//                        for (int j = 0; j < item_arr.length(); j++) {
//
//                            JSONObject object2 = item_arr.optJSONObject(j);
//
//                            InsuranceSelectAdapter.InsuranceItem list = new InsuranceSelectAdapter.InsuranceItem();
//
//                            list.NAME = object2.optString("detailname");
//
//                            String money = object2.optString("detailtype");
//
//                            String[] moneyList = money.split(",");
//
//                            String price = object2.optString("detailprice");
//
//                            String[] priceList = price.split(",");
//
//                            list.ITEM_PRICE = new ArrayList<>();
//
//                            InsuranceSelectAdapter.InsuranceItemPrice list3 = new InsuranceSelectAdapter.InsuranceItemPrice();
//
//                            list3.MONEY = "不投保";
//
//                            list3.PRICE = "0";
//
//                            list.ITEM_PRICE.add(list3);
//
//                            if (moneyList.length == priceList.length) {
//
//                                for (int k = 0; k < moneyList.length; k++) {
//
//                                    InsuranceSelectAdapter.InsuranceItemPrice list2 = new InsuranceSelectAdapter.InsuranceItemPrice();
//
//                                    list2.MONEY = moneyList[k];
//
//                                    list2.PRICE = priceList[k];
//
//                                    list.ITEM_PRICE.add(list2);
//
//                                }
//                            }
//
//                            insuranceItemList.add(list);
//
//                        }
//
//                        mbundle.putSerializable("ITEM_LIST", (Serializable) insuranceItemList);
//
//                        i.putExtras(mbundle);
//
//                        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                        context.startActivity(i);
//                    }


                } else if (message_type.equals("8")) {
                    //4S店预约


//                    Intent i = new Intent(context, OrderDetailsActivity.class);
//
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                    i.putExtra("TYPE", String.valueOf(jsonObject_value.optInt("OPERSTATE")));
//
//                    i.putExtra("FLAG", "1");//订单页跳转
//
//                    i.putExtra("OPERSTATE", String.valueOf(jsonObject_value.optInt("OPERSTATE")));
//
//                    i.putExtra("JSID", String.valueOf(jsonObject_value.optInt("JSID")));
//
//                    i.putExtra("ORDERID", jsonObject_value.optString("ORDERID"));
//
//                    i.putExtra("PRE_TIME", jsonObject_value.optString("PRE_TIME"));
//
//                    i.putExtra("JSNAME", jsonObject_value.optString("JSNAME"));
//
//                    JSONArray order_arr = jsonObject_value.optJSONArray("LIST");
//
//                    fields = new ArrayList<>();
//
//                    if (order_arr != null) {
//
//                        for (int j = 0; j < order_arr.length(); j++) {
//
//                            JSONObject object2 = order_arr.optJSONObject(j);
//
//                            GetMyOrder1.Field list2 = new GetMyOrder1.Field();
//
//                            list2.PRICE = object2.optString("PRICE");
//
//                            list2.ORDER_NUM = jsonObject_value.optString("ORDERID");
//
//                            list2.NAME = object2.optString("NAME");
//
//                            list2.GOODS_ID = object2.optString("GOODS_ID");
//
//                            list2.NUM = object2.optString("NUM");
//
//                            fields.add(list2);
//
//                        }
//
//                        Bundle mbundle = new Bundle();
//
//                        mbundle.putSerializable("LIST", (Serializable) fields);
//
//                        i.putExtras(mbundle);
//                    }
//
//
//                    JTApplication.INSTANCE.finishActivity(OrderDetailsActivity.class);
//
//                    context.startActivity(i);


                } else if (message_type.equals("9")) {
                    //4S店支付

                } else if (message_type.equals("10")) {
                    //4S店退款

                } else if (message_type.equals("11")) {
                    //加油站预约

                } else if (message_type.equals("12")) {
                    //加油站支付

                } else if (message_type.equals("13")) {
                    //加油站加油

                } else if (message_type.equals("14")) {
                    //加油站退款

                } else if (message_type.equals("15")) {
                    //购险报价

                    JTApplication.jtPreferences.saveInsFlag("2");

                    Intent i = new Intent(context, InsQuoteActivity.class);

                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    JTApplication.INSTANCE.finishActivity(InsCheckSelectActivity.class);

                    context.startActivity(i);

                } else if (message_type.equals("16")) {
                    //购险精准报价

//                    JTApplication.jtPreferences.saveInsFlag("4");
//
//                    JTApplication.INSTANCE.finishActivity(NewWaitPricingActivity.class);
//
//                    Intent i = new Intent(context, NewWaitPricingActivity.class);
//
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                    context.startActivity(i);

                } else if (message_type.equals("17")) {
                    //行程报告
                    Intent i = new Intent(context, TravelReportActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    i.putExtra("id", value);
                    context.startActivity(i);


                } else if (message_type.equals("18")) {
                    //4S店退款

                } else if (message_type.equals("19")) {
                    //安全驾驶奖励积分

//                    Intent i = new Intent(context, GetIntegralActivity.class)
//
//                            .putExtra("type",message_level)
//
//                            .putExtra("num", value)
//
//                            .putExtra("messageId", message_id);
//
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                    context.startActivity(i);

                }

                else if (message_type.equals("30")) {
                    //高速公路相关

                    JTApplication.INSTANCE.finishActivity(FreeWayStateShowActivity.class);

                    Intent i = new Intent(context, FreeWayStateShowActivity.class)

                            .putExtra("value",value)

                            .putExtra("message", message);

                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    context.startActivity(i);

                }

                else if (message_type.equals("31")) {
                    //高速公路开通服务

//                    Intent i = new Intent(context, PersonActivity.class);
//
//                    Bundle mbundle = new Bundle();
//
//                    mbundle.putString("value",value);
//
//                    JTApplication.jtPreferences.saveFreeway(value);
//
//                    i.putExtras(mbundle);
//
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//
//                    JTApplication.INSTANCE.finishActivity(PersonActivity.class);
//
//                    context.startActivity(i);

                }

//        	//打开自定义的Activity
//        	Intent i = new Intent(context, TestActivity.class);
//        	i.putExtras(bundle);
//        	//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        	i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
//        	context.startActivity(i);

            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.d(TAG, "[JPushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, "[JPushReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Log.d(TAG, "[JPushReceiver] Unhandled intent - " + intent.getAction());
            }
        }

    }


    // 打印所有的 intent extra 数据

    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next().toString();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
//		if (MainActivity.isForeground) {
//			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
//			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
//			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
//			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
//			if (!ExampleUtil.isEmpty(extras)) {
//				try {
//					JSONObject extraJson = new JSONObject(extras);
//					if (null != extraJson && extraJson.length() > 0) {
//						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
//					}
//				} catch (JSONException e) {
//
//				}
//
//			}
//			context.sendBroadcast(msgIntent);
//		}
    }
}
